# coding:utf-8
from dataclasses import dataclass
import re
import os
import sys
import json
from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtWidgets import QWidget, QHBoxLayout, QSpacerItem, QSizePolicy, QCompleter
from qfluentwidgets import (
    SearchLineEdit,
    PushButton,
)
from qframelesswindow.webengine import FramelessWebEngineView

from service.stock_service import StockMainService


from .base_gallery_view import GalleryInterface
from .common.translator import Translator
from .base_gallery_view import GalleryInterface
from config.log_config import AntLogger

@dataclass
class ShowViewConfig:

    # 展示顶部搜索栏 ：
    show_top: bool


class BaseInfoTemplateView(GalleryInterface):
    """Scroll interface"""

    def __init__(self, objectName, parent=None):
        t = Translator()
        super().__init__(
            title=t.scroll, subtitle="qfluentwidgets.components.widgets", parent=parent
        )
        self.setObjectName(objectName)
        self.loaded = False
        self.searchKey = ""

        # 添加顶部搜索框
        if self.getViewConfig().show_top:
            self.topView = TopTemplate(self, self)
            self.vBoxLayout.addWidget(self.topView)

        # 添加底部操作栏
        self.mainView = MainTemplate(self)
        self.vBoxLayout.addWidget(self.mainView)

        if not self.getViewConfig().show_top:
            self.updateEchatData()

    def showEvent(self, event):
        super().showEvent(event)
        if not self.loaded:
            self.loaded = True
            self.doInitAndUpdate()

    def addTopWidget(self, itemWidget: QWidget):
        self.topView.addTopWidget(itemWidget)

    def doSearch(self):
        print(f"...点击查询按钮{self.searchKey}")

    def refreshDate(self):
        self.doSearch()

    def addEcahtMainView(self, chatName: str):
        self.chatView = EchatTemplate(chatName, self)
        self.mainView.addMainWidget(self.chatView)

    def getEchatData(self, jsonData: dict):
        print(f"...点击查询指定对象{self.searchKey}")

    def updateEchatData(self):
        self.chatView.onLoadFinished()

    def getAllStock(self):
        stockService = StockMainService()
        return stockService.getAllStockListSample()

    def getViewConfig(self):
        return ShowViewConfig(True)


class TopTemplate(QWidget):
    def __init__(self, outView: BaseInfoTemplateView, parent=None):
        super().__init__(parent=parent)
        self.outView = outView

        # 顶部搜索框
        self.searchLineEdit = TopTemplateSearchLineEdit(self)
        stands = self.getAllStock()
        completer = QCompleter(stands, self.searchLineEdit)
        completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        completer.setMaxVisibleItems(10)
        self.searchLineEdit.setCompleter(completer)

        self.searchLineEdit.clearSignal.connect(self.refreshDate)
        self.searchLineEdit.searchSignal.connect(self.doSearch)

        # 中间格挡
        self.spacer = QSpacerItem(
            20, 10, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum
        )

        # 默认按钮
        self.updateButton = PushButton(self.tr("刷新所有"))
        self.updateButton.setFixedWidth(120)
        self.updateButton.clicked.connect(self.refreshDate)

        self.hBoxLayout = QHBoxLayout()

        self.__initWidget()

    def __initWidget(self):

        self.hBoxLayout.setSpacing(0)
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.hBoxLayout.addWidget(self.searchLineEdit)

        self.hBoxLayout.addStretch(1)
        self.hBoxLayout.addItem(self.spacer)
        self.hBoxLayout.addWidget(self.updateButton)

        self.setLayout(self.hBoxLayout)

    def addTopWidget(self, itemWidget: QWidget):
        self.hBoxLayout.addWidget(itemWidget)

    def doSearch(self, keyWord: str):
        self.outView.searchKey = keyWord
        self.outView.doSearch()

    def refreshDate(self):
        self.outView.refreshDate()

    def getAllStock(self):
        self.outView.getAllStock()


class TopTemplateSearchLineEdit(SearchLineEdit):
    """Search line edit"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setPlaceholderText(self.tr("通过股票代码/名称查询"))
        self.setFixedWidth(304)


class MainTemplate(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.hBoxLayout = QHBoxLayout()

        self.__initWidget()

    def __initWidget(self):

        # 默认中间模板是水平结构
        self.setLayout(self.hBoxLayout)

    def addMainWidget(self, itemWidget: QWidget):
        self.hBoxLayout.addWidget(itemWidget)


class EchatTemplate(QWidget):
    def __init__(self, chatName: str, outView: BaseInfoTemplateView, parent=None):
        super().__init__(parent=parent)
        self.setMinimumSize(600, 800)
        self.webView = FramelessWebEngineView(self)

        # 开启前端调试
        # self.webView.showDevTools()
        self.chatName = chatName
        self.outView = outView

        current_dir = os.path.dirname(os.path.abspath(__file__)) + "\\common\\html\\"
        chatHTMLFile = self.chatName + ".html"
        self.chatPath = os.path.join(current_dir, chatHTMLFile)
        self.webView.load(QUrl.fromLocalFile(self.chatPath))

        self.hBoxLayout = QHBoxLayout()
        self.__initWidget()

    def __initWidget(self):
        self.webView.loadFinished.connect(self.onLoadFinished)
        self.hBoxLayout.addWidget(self.webView)
        self.setLayout(self.hBoxLayout)

    def getChatData(self):
        current_dir = os.path.dirname(os.path.abspath(__file__)) + "\\common\\html\\"
        chatJSONFile = self.chatName + ".json"
        local_file_path = os.path.join(current_dir, chatJSONFile)

        json_data = ""
        with open(local_file_path, "r", encoding="utf-8") as file:
            json_data = json.load(file)

        return self.outView.getEchatData(json_data)

    def onLoadFinished(self):
        # 页面加载完成后，调用 JavaScript 的 setData 函数

        before_exchange = self.getChatData()

        js_code = f"setData({before_exchange});"
        # print(f"最终写入参数{js_code}")
        self.webView.page().runJavaScript(js_code, self.js_callback)

    def js_callback(self, result):
        print(f"前端操作加载完成[Tempate]: {result}")
